<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryRef"
     :inline="true" v-show="showSearch" label-width="80px">
      
     
      
      <el-form-item label="投票标题" prop="voteTitle">
        <el-input  v-model="queryParams.voteTitle" placeholder="请输入投票标题" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable style="width: 200px">
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createDate">
        <el-date-picker
          v-model="queryParams.createDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['pms:vote:add']">新增</el-button>
      </el-col>
      
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate()"
          v-hasPermi="['pms:vote:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pms:vote:remove']"
        >删除</el-button>
      </el-col>
     
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table border v-loading="loading" :data="voteList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="类型" prop="type" align="center" width="100px">
        <template #default="scope">
          {{ typeOptions.find(item => item.value === scope.row.type)?.label || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="标题"   prop="voteTitle" align="center" width="200px" />
      <el-table-column label="内容" prop="voteContent" align="center" 
       :show-overflow-tooltip="true" width="200px" >
       <template #default="scope">
        <div v-html="scope.row.voteContent"></div>
       </template>
      </el-table-column>
      <el-table-column label="投票范围" prop="voteScope" align="center" width="220px" >
        <template #default="scope">
          {{ (scope.row.voteScope || '').split(',').map(val => voteScopeOptions.find(opt => opt.value === val)?.label).filter(Boolean).join(', ') }}
        </template>
      </el-table-column>
      <el-table-column label="查看范围" prop="voteViewScope" align="center" width="220px">
        <template #default="scope">
          {{ (scope.row.voteViewScope || '').split(',').map(val => voteScopeOptions.find(opt => opt.value === val)?.label).filter(Boolean).join(', ') }}
        </template>
      </el-table-column>
      <el-table-column label="投票规则" prop="voteRule" align="center" width="170px">
        <template #default="scope">
          {{ voteRuleOptions.find(item => item.value === scope.row.voteRule)?.label }}
        </template>
      </el-table-column>
      <el-table-column label="通过比例/目标签字人数" prop="ratio" required align="center" width="200px" >
        <template #default="scope">
          {{ scope.row.type === 2 ? (scope.row.ratio + '%') : scope.row.type === 4 ? (scope.row.signNum )+"人" : '-'  }}
        </template>
      </el-table-column>
      <el-table-column label="投票时间段" align="center" width="360">
        <template #default="scope">
          <span>{{ scope.row.startDate }} 至 {{ scope.row.endDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" prop="createName" align="center" />
      <el-table-column label="创建时间" prop="createDate" align="center"  width="200px"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="250">
        <template #default="scope">
             <!-- <el-button link
           type="primary" icon="Edit" @click="handleCopy(scope.row)"
            v-hasPermi="['pms:vote:edit']">复制</el-button> -->
          <el-button link
           type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['pms:vote:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete"
           @click="handleDelete(scope.row)" v-hasPermi="['pms:vote:remove']">删除</el-button>
            <el-button link
           type="primary" icon="MessageBox" @click="handleView(scope.row)" 
            v-hasPermi="['pms:record:list']">查看记录</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 新增/修改弹窗 -->
    <el-dialog :title="title" v-model="open"
     width="800px" @close="cancel" :close-on-click-modal="false" append-to-body>
      <el-form ref="voteRef" :model="form" :rules="rules" label-width="120px">
        <!-- <el-form-item label="小区" prop="communityId">
          <el-select v-model="form.communityId" placeholder="请选择小区" style="width: 100%">
            <el-option v-for="item in communityOptions" :key="item.communityId" :label="item.name" :value="item.communityId" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型" style="width: 100%" @change="handleTypeChange">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="投票标题" prop="voteTitle">
          <el-input v-model="form.voteTitle" placeholder="请输入投票标题" />
        </el-form-item>
         
        <el-form-item label="投票图片" prop="votePicture">
          <image-upload  limit="1" v-model="form.votePicture" />
        </el-form-item>
       
          <el-form-item label="投票时间" prop="dateRange">
          <el-date-picker
            v-model="form.dateRange"
            type="datetimerange"
            value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :disabled-date="disabledDate"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="投票范围" prop="voteScope">
          <el-select v-model="form.voteScope" multiple placeholder="请选择投票范围" style="width: 100%">
            <el-option
              v-for="item in voteScopeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="查看范围" prop="voteViewScope" v-if="form.type && form.type !== 4">
          <el-select v-model="form.voteViewScope" multiple placeholder="请选择投票范围" style="width: 100%">
            <el-option
              v-for="item in voteScopeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>

          <!-- <el-input v-model="form.voteViewScope" placeholder="请输入查看范围" /> -->
        </el-form-item>
        <el-form-item label="投票规则" prop="voteRule" required v-if="form.type && form.type !== 3 && form.type !== 4">
          <el-select v-model="form.voteRule" placeholder="请选择投票规则" style="width: 100%">
            <el-option
              v-for="item in voteRuleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="通过比例" prop="ratio" required v-if="form.type === 2">
          <el-input-number 
            v-model="form.ratio" 
            :min="0.001" 
            :max="100" 
            :precision="3"
            :step="0.001"
            placeholder="请输入通过比例(%)" 
            style="width: 100%"
          />
         
        </el-form-item>

        <el-form-item label="目标签字人数" prop="signNum" required v-if="form.type === 4">
          <el-input-number 
            v-model="form.signNum" 
            :min="1" 
            :precision="0"
            placeholder="请输入目标签字人数" 
            style="width: 100%"
          />
        </el-form-item>
      
      <!-- 投票选项部分 -->
      <el-form-item label="投票选项" required prop="voteOptions" v-if="form.type && form.type !== 4">
        <div style="width: 100%;">
          <!-- 普通投票模式 - 改为多问题结构，支持单选多选 -->
          <div v-if="form.type === 1">
            <div v-for="(question, qIdx) in voteQuestions" :key="qIdx" style="margin-bottom: 20px;">
              <el-card shadow="never" style="border-radius: 8px;">
                <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px;">
                  <span style="font-weight: bold; color: #333;">问题 {{ qIdx + 1 }}</span>
                  <div>
                    <el-button type="primary" circle icon="Plus" @click="addVoteQuestion" style="margin-right: 8px;" />
                    <el-button type="danger" circle icon="Minus" @click="removeVoteQuestion(qIdx)" :disabled="voteQuestions.length === 1" />
                  </div>
                </div>
                
                <!-- 问题标题 -->
                <div style="margin-bottom: 16px;">
                  <div style="display: flex; align-items: center;">
                    <span style="width: 80px; color: #888;">问题标题</span>
                    <el-input v-model="question.title" placeholder="请输入问题标题" style="flex:1;" />
                  </div>
                </div>

                <!-- 问题备注 -->
                <div style="margin-bottom: 16px;">
                  <div style="display: flex; align-items: center;">
                    <span style="width: 80px; color: #888;">问题备注</span>
                    <el-input v-model="question.remark" placeholder="请输入问题备注（可选）" style="flex:1;" />
                  </div>
                </div>

                <!-- 问题类型 -->
                <div style="margin-bottom: 16px;">
                  <div style="display: flex; align-items: center;">
                    <span style="width: 80px; color: #888;">问题类型</span>
                    <el-select v-model="question.optionType" placeholder="请选择问题类型" style="flex:1;">
                      <el-option :value="1" label="单选" />
                      <el-option :value="2" label="多选" />
                      <!-- <el-option :value="3" label="填空" /> -->
                    </el-select>
                  </div>
                </div>
      
                <!-- 投票限制（多选时显示） -->
                <div v-if="question.optionType === 2" style="margin-bottom: 16px;">
                  <!-- 限制类型选择 -->
                  <div style="display: flex; align-items: center; margin-bottom: 12px;">
                    <span style="width: 80px; color: #888;">选择限制</span>
                    <el-select v-model="question.limitType" placeholder="请选择限制类型" style="flex:1;" @change="handleVoteLimitTypeChange(qIdx)">
                      <el-option :value="1" label="区间限制（X-Y个）" />
                      <el-option :value="2" label="最少限制（至少X个）" />
                      <el-option :value="3" label="最多限制（最多X个）" />
                      <el-option :value="4" label="固定数量（只能X个）" />
                      <el-option :value="5" label="无限制" />
                    </el-select>
                  </div>
                  
                  <!-- 根据限制类型显示不同的输入框 -->
                  <div v-if="question.limitType === 1" style="display: flex; align-items: center; gap: 16px;">
                    <div style="display: flex; align-items: center; flex: 1;">
                      <span style="width: 80px; color: #888;">最少选择</span>
                      <el-input-number 
                        v-model="question.minNum" 
                        :min="1" 
                        :max=" 99"
                        :precision="0"
                        placeholder="最少选择数" 
                        style="flex:1;"
                      />
                      <span style="margin-left: 8px; color: #888;">项</span>
                    </div>
                    <div style="display: flex; align-items: center; flex: 1;">
                      <span style="width: 80px; color: #888;">最多选择</span>
                      <el-input-number 
                        v-model="question.maxNum" 
                        :min="question.minNum || 1" 
                        max="999"
                        :precision="0"
                        placeholder="最多选择数" 
                        style="flex:1;"
                      />
                      <span style="margin-left: 8px; color: #888;">项</span>
                    </div>
                  </div>
                  
                  <div v-else-if="question.limitType === 2" style="display: flex; align-items: center;">
                    <span style="width: 80px; color: #888;">最少选择</span>
                    <el-input-number 
                      v-model="question.minNum" 
                      :min="1" 
                      :max="question.options.length"
                      :precision="0"
                      placeholder="最少选择数" 
                      style="flex:1;"
                    />
                    <span style="margin-left: 8px; color: #888;">项（无上限）</span>
                  </div>
                  
                  <div v-else-if="question.limitType === 3" style="display: flex; align-items: center;">
                    <span style="width: 80px; color: #888;">最多选择</span>
                    <el-input-number 
                      v-model="question.maxNum" 
                      :min="1" 
                      :max="question.options.length"
                      :precision="0"
                      placeholder="最多选择数" 
                      style="flex:1;"
                    />
                    <span style="margin-left: 8px; color: #888;">项（无下限）</span>
                  </div>
                  
                  <div v-else-if="question.limitType === 4" style="display: flex; align-items: center;">
                    <span style="width: 80px; color: #888;">固定数量</span>
                    <el-input-number 
                      v-model="question.fixedNum" 
                      :min="1" 
                      :max="question.options.length"
                      :precision="0"
                      placeholder="固定选择数" 
                      style="flex:1;"
                      @change="handleFixedNumChange(qIdx)"
                    />
                    <span style="margin-left: 8px; color: #888;">项</span>
                  </div>
                  
                  <div v-else-if="question.limitType === 5" style="color: #909399; font-size: 14px; padding-left: 80px;">
                    用户可以选择任意数量的选项（0到全部）
                  </div>
                </div>
                
                <!-- 问题选项 -->
                <div style="margin-bottom: 12px;">
                  <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px;">
                    <span style="color: #666;">选项</span>
                    <div>
                      <el-button type="primary" size="small" icon="Plus" @click="addVoteQuestionOption(qIdx)" style="margin-right: 4px;" />
                      <el-button type="danger" size="small" icon="Minus" @click="removeVoteQuestionOption(qIdx)" :disabled="question.options.length === 1" />
                    </div>
                  </div>
                  <div v-for="(option, oIdx) in question.options" :key="oIdx" style="margin-bottom: 8px;">
                    <div style="display: flex; align-items: center;">
                      <span style="width: 60px; color: #888; font-size: 12px;">选项{{ oIdx + 1 }}</span>
                      <el-input v-model="option.name" placeholder="请输入选项名称" style="flex:1;" />
                    </div>
                  </div>
                </div>
              </el-card>
            </div>
          </div>
          
          <!-- 快速决议模式 -->
          <div v-if="form.type === 2">
            <div v-for="(question, qIdx) in voteQuestions" :key="qIdx" style="margin-bottom: 20px;">
              <el-card shadow="never" style="border-radius: 8px;">
                <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px;">
                  <span style="font-weight: bold; color: #333;">问题 {{ qIdx + 1 }}</span>
                  <div>
                    <el-button type="primary" circle icon="Plus" @click="addQuestion" style="margin-right: 8px;" />
                    <el-button type="danger" circle icon="Minus" @click="removeQuestion(qIdx)" :disabled="voteQuestions.length === 1" />
                  </div>
                </div>
                
                <!-- 问题标题 -->
                <div style="margin-bottom: 16px;">
                  <div style="display: flex; align-items: center;">
                    <span style="width: 80px; color: #888;">问题标题</span>
                    <el-input v-model="question.title" placeholder="请输入问题标题" style="flex:1;" />
                  </div>
                </div>
                
                <!-- 问题选项 -->
                <div style="margin-bottom: 12px;">
                  <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px;">
                    <span style="color: #666;">选项</span>
                    <div>
                      <el-button type="primary" size="small" icon="Plus" @click="addQuestionOption(qIdx)" style="margin-right: 4px;" />
                      <el-button type="danger" size="small" icon="Minus" @click="removeQuestionOption(qIdx)" :disabled="question.options.length === 1" />
                    </div>
                  </div>
                  <div v-for="(option, oIdx) in question.options" :key="oIdx" style="margin-bottom: 8px;">
                    <div style="display: flex; align-items: center;">
                      <span style="width: 60px; color: #888; font-size: 12px;">选项{{ oIdx + 1 }}</span>
                      <el-input v-model="option.name" placeholder="请输入选项名称" style="flex:1;" />
                    </div>
                  </div>
                </div>
              </el-card>
            </div>
          </div>

          <!-- 问卷调查模式 -->
          <div v-if="form.type === 3">
            <div v-for="(question, qIdx) in surveyQuestions" :key="qIdx" style="margin-bottom: 20px;">
              <el-card shadow="never" style="border-radius: 8px;">
                <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px;">
                  <span style="font-weight: bold; color: #333;">问题 {{ qIdx + 1 }}</span>
                  <div>
                    <el-button type="primary" circle icon="Plus" @click="addSurveyQuestion" style="margin-right: 8px;" />
                    <el-button type="danger" circle icon="Minus" @click="removeSurveyQuestion(qIdx)" :disabled="surveyQuestions.length === 1" />
                  </div>
                </div>
                
                <!-- 问题标题 -->
                <div style="margin-bottom: 16px;">
                  <div style="display: flex; align-items: center;">
                    <span style="width: 80px; color: #888;">问题标题</span>
                    <el-input v-model="question.title" placeholder="请输入问题标题" style="flex:1;" />
                  </div>
                </div>

                <!-- 问题类型 -->
                <div style="margin-bottom: 16px;">
                  <div style="display: flex; align-items: center;">
                    <span style="width: 80px; color: #888;">问题类型</span>
                    <el-select v-model="question.optionType" placeholder="请选择问题类型" style="flex:1;">
                      <el-option :value="1" label="单选" />
                      <el-option :value="2" label="多选" />
                      <!-- <el-option :value="3" label="填空" /> -->
                    </el-select>
                  </div>
                </div>

                <!-- 投票限制（多选时显示） -->
                <div v-if="question.optionType === 2" style="margin-bottom: 16px;">
                  <!-- 限制类型选择 -->
                  <div style="display: flex; align-items: center; margin-bottom: 12px;">
                    <span style="width: 80px; color: #888;">选择限制</span>
                    <el-select v-model="question.limitType" placeholder="请选择限制类型" style="flex:1;" @change="handleSurveyLimitTypeChange(qIdx)">
                      <el-option :value="1" label="区间限制（X-Y个）" />
                      <el-option :value="2" label="最少限制（至少X个）" />
                      <el-option :value="3" label="最多限制（最多X个）" />
                      <el-option :value="4" label="固定数量（只能X个）" />
                      <el-option :value="5" label="无限制" />
                    </el-select>
                  </div>
                  
                  <!-- 根据限制类型显示不同的输入框 -->
                  <div v-if="question.limitType === 1" style="display: flex; align-items: center; gap: 16px;">
                    <div style="display: flex; align-items: center; flex: 1;">
                      <span style="width: 80px; color: #888;">最少选择</span>
                      <el-input-number 
                        v-model="question.minNum" 
                        :min="1" 
                        :max="question.maxNum || 99"
                        :precision="0"
                        placeholder="最少选择数" 
                        style="flex:1;"
                      />
                      <span style="margin-left: 8px; color: #888;">项</span>
                    </div>
                    <div style="display: flex; align-items: center; flex: 1;">
                      <span style="width: 80px; color: #888;">最多选择</span>
                      <el-input-number 
                        v-model="question.maxNum" 
                        :min="question.minNum || 1" 
                        :max="question.options.length"
                        :precision="0"
                        placeholder="最多选择数" 
                        style="flex:1;"
                      />
                      <span style="margin-left: 8px; color: #888;">项</span>
                    </div>
                  </div>
                  
                  <div v-else-if="question.limitType === 2" style="display: flex; align-items: center;">
                    <span style="width: 80px; color: #888;">最少选择</span>
                    <el-input-number 
                      v-model="question.minNum" 
                      :min="1" 
                      :max="question.options.length"
                      :precision="0"
                      placeholder="最少选择数" 
                      style="flex:1;"
                    />
                    <span style="margin-left: 8px; color: #888;">项（无上限）</span>
                  </div>
                  
                  <div v-else-if="question.limitType === 3" style="display: flex; align-items: center;">
                    <span style="width: 80px; color: #888;">最多选择</span>
                    <el-input-number 
                      v-model="question.maxNum" 
                      :min="1" 
                      :max="question.options.length"
                      :precision="0"
                      placeholder="最多选择数" 
                      style="flex:1;"
                    />
                    <span style="margin-left: 8px; color: #888;">项（无下限）</span>
                  </div>
                  
                  <div v-else-if="question.limitType === 4" style="display: flex; align-items: center;">
                    <span style="width: 80px; color: #888;">固定数量</span>
                    <el-input-number 
                      v-model="question.fixedNum" 
                      :min="1" 
                      :max="question.options.length"
                      :precision="0"
                      placeholder="固定选择数" 
                      style="flex:1;"
                      @change="handleSurveyFixedNumChange(qIdx)"
                    />
                    <span style="margin-left: 8px; color: #888;">项</span>
                  </div>
                  
                  <div v-else-if="question.limitType === 5" style="color: #909399; font-size: 14px; padding-left: 80px;">
                    用户可以选择任意数量的选项（1到全部）
                  </div>
                </div>
                
                <!-- 问题选项（单选和多选时显示） -->
                <div style="margin-bottom: 12px;" v-if="question.optionType === 1 || question.optionType === 2">
                  <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px;">
                    <span style="color: #666;">选项</span>
                    <div>
                      <el-button type="primary" size="small" icon="Plus" @click="addSurveyOption(qIdx)" style="margin-right: 4px;" />
                      <el-button type="danger" size="small" icon="Minus" @click="removeSurveyOption(qIdx)" :disabled="question.options.length === 1" />
                    </div>
                  </div>
                  <div v-for="(option, oIdx) in question.options" :key="oIdx" style="margin-bottom: 8px;">
                    <div style="display: flex; align-items: center;">
                      <span style="width: 60px; color: #888; font-size: 12px;">选项{{ oIdx + 1 }}</span>
                      <el-input v-model="option.name" placeholder="请输入选项名称" style="flex:1; margin-right: 8px;" />
                      <el-button 
                        type="danger" 
                        size="small" 
                        icon="Delete" 
                        @click="removeSurveyOptionItem(qIdx, oIdx, option.optionId)"
                        :disabled="question.options.length === 1"
                      />
                    </div>
                  </div>
                </div>
              </el-card>
            </div>
          </div>
        </div>
      </el-form-item>
           <el-form-item label="补充信息" prop="remark" v-if="form.type && form.type !== 4">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入补充信息" />
        </el-form-item>
         <el-form-item label="发起方" prop="initiator">
          <el-input  v-model="form.initiator" placeholder="请输入发起方" />
        </el-form-item>
          <el-form-item label="手机号" prop="mobile" v-if="form.type && form.type !== 4">
          <el-input  v-model="form.mobile" placeholder="请输入手机号" />
        </el-form-item>
         <el-form-item label="投票内容" prop="voteContent" v-if="form.type && form.type !== 4">
            <editor v-model="form.voteContent" :min-height="192"/>
        </el-form-item>
         
         <el-form-item label="相关材料" prop="fileUrl" >
           <FileUpload 
                v-model="form.fileUrl"
                :file-type="['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'pdf', 'jpg', 'jpeg', 'png']"
                :file-size="10"
                :limit="5"
              />
        </el-form-item>
        <el-form-item label="倡议书内容" prop="voteContent" v-if="form.type === 4">
            <editor v-model="form.voteContent" :min-height="192"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入弹窗 -->
    <el-dialog 
    :align-center="true"
    v-model="importDialogVisible"
     title="导入投票" width="700px"
      :close-on-click-modal="false">
      <el-upload
        class="upload-demo"
        :action="uploadFileUrl"
        :show-file-list="true"
        :headers="headers"
        :limit="1"
        :on-success="handleImportSuccess"
        :on-exceed="handleExceed"
          
      >
      <div class="upload-demo-btn" style="border: 1px dashed #d9d9d9;border-radius: 6px;cursor: pointer;position: relative;overflow: hidden;transition: all .3s;">
         <el-icon size="50" class="el-icon--upload"><upload-filled /></el-icon>
        <div class="upload-demo-btn-text">导入Excel</div>
        <div class="upload-demo-btn-text-desc">
          将文件拖拽到此处或<span> 点击上传</span>，只能支持xlsx,xls文件</div>
      </div>
        <template #tip>
          <div class="el-upload__tip">只支持上传1个文件，格式不限，选择后自动上传</div>
        </template>
      </el-upload>
      <template #footer>
        
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { nextTick } from 'vue'
import { listVote, delVote, addVote, updateVote, getVote, delVoteOption } from "@/api/house/vote";
import { listCommunity } from "@/api/house/room"; // Assuming community list is here
import useUserStore from '@/store/modules/user'
import { getToken } from "@/utils/auth"
import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = useUserStore()
const { proxy } = getCurrentInstance();

const voteList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const communityOptions = ref([]);
const importDialogVisible = ref(false)
const importFile = ref(null)
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/pms/house/importData") // 上传文件服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() })
const voteScopeOptions = ref([
  { value: '1', label: '业主' },
  { value: '2', label: '家属' },
  { value: '3', label: '租客' },
  { value: '4', label: '游客' },
]);

const voteRuleOptions = ref([
  { value: 1, label: '每人投一票（单选）' },
  { value: 2, label: '每人投一票多选' },
  { value: 3, label: '每户投一票（单选）' },
  { value: 4, label: '每户投一票多选' },
]);

const typeOptions = ref([
  { value: 1, label: '投票' },
  { value: 2, label: '快速决议' },
  { value: 3, label: '问卷调查' },
  { value: 4, label: '发起倡议书' },
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: null,
    voteTitle: null,
    createDate: null,
  },
  rules: {
    communityId: [{ required: true, message: "小区不能为空", trigger: "change" }],
    type: [{ required: true, message: "类型不能为空", trigger: "change" }],
    voteTitle: [{ required: true, message: "投票标题不能为空", trigger: "blur" }],
    voteContent: [{ required: true, message: "投票内容不能为空", trigger: "blur" }],
    dateRange: [{ 
      required: true, 
      // message: "投票时间不能为空", 
      trigger: "change",
      validator: (rule, value, callback) => {
        // 检查是否为空（null、undefined、空数组）
        if (!value || (Array.isArray(value) && value.length === 0)) {
          callback(new Error('请选择投票时间范围'));
          return;
        }
        
        // 检查是否为数组且长度为2
        if (!Array.isArray(value) || value.length !== 2) {
          callback(new Error('请选择完整的投票时间范围'));
          return;
        }
        
        const [startTime, endTime] = value;
        
        // 检查开始时间和结束时间是否都存在
        if (!startTime || !endTime) {
          callback(new Error('请选择完整的投票时间范围'));
          return;
        }
        
        const now = new Date();
        const startDate = new Date(startTime);
        const endDate = new Date(endTime);
        
        // 检查日期是否有效
        if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
          callback(new Error('时间格式不正确'));
          return;
        }
        
        if(title.value!="修改投票"){

        

        // 检查开始时间是否大于等于当前时间（允许选择今天，但时间要合理）
        if (startDate < now) {
          callback(new Error('开始时间不能早于当前时间，请选择更晚的时间'));
          return;
        }
        
        // 检查结束时间是否大于开始时间
        if (endDate <= startDate) {
          callback(new Error('结束时间必须大于开始时间'));
          return;
        }
      }
        callback();
      }
    }],
    voteScope: [{ required: true, message: "投票范围不能为空", trigger: "change" }],
    voteRule: [{ 
      required: false, 
      trigger: "change",
      validator: (rule, value, callback) => {
        if (form.value.type !== 3 && form.value.type !== 4) {
          if (!value) {
            callback(new Error('投票规则不能为空'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      }
    }],
    voteOptions: [{ 
      required: false, 
      trigger: "blur",
      validator: (rule, value, callback) => {
        if (form.value.type === 1) {
          // 类型为1（投票）时，检查voteQuestions数组
          if (!voteQuestions.value || voteQuestions.value.length === 0) {
            callback(new Error('问题不能为空'));
            return;
          }
          // 检查每个问题是否有标题和选项
          for (let i = 0; i < voteQuestions.value.length; i++) {
            const question = voteQuestions.value[i];
            if (!question.title || question.title.trim() === '') {
              callback(new Error(`问题${i + 1}的标题不能为空`));
              return;
            }
            if (!question.optionType) {
              callback(new Error(`问题${i + 1}的问题类型不能为空`));
              return;
            }
            if (!question.options || question.options.length === 0) {
              callback(new Error(`问题${i + 1}的选项不能为空`));
              return;
            }
            // 检查选项名称
            for (let j = 0; j < question.options.length; j++) {
              if (!question.options[j].name || question.options[j].name.trim() === '') {
                callback(new Error(`问题${i + 1}的选项${j + 1}名称不能为空`));
                return;
              }
            }
          }
          callback();
        } else if (form.value.type === 2) {
          // 类型为2（快速决议）时，检查voteQuestions
          if (!voteQuestions.value || voteQuestions.value.length === 0) {
            callback(new Error('问题不能为空'));
            return;
          }
          // 检查每个问题是否有标题和选项
          for (let i = 0; i < voteQuestions.value.length; i++) {
            const question = voteQuestions.value[i];
            if (!question.title || question.title.trim() === '') {
              callback(new Error(`问题${i + 1}的标题不能为空`));
              return;
            }
            if (!question.options || question.options.length === 0) {
              callback(new Error(`问题${i + 1}的选项不能为空`));
              return;
            }
            // 检查选项名称
            for (let j = 0; j < question.options.length; j++) {
              if (!question.options[j].name || question.options[j].name.trim() === '') {
                callback(new Error(`问题${i + 1}的选项${j + 1}名称不能为空`));
                return;
              }
            }
          }
          callback();
        } else if (form.value.type === 3) {
          // 类型为3（问卷调查）时，检查surveyQuestions
          if (!surveyQuestions.value || surveyQuestions.value.length === 0) {
            callback(new Error('问题不能为空'));
            return;
          }
          // 检查每个问题是否有标题
          for (let i = 0; i < surveyQuestions.value.length; i++) {
            const question = surveyQuestions.value[i];
            if (!question.title || question.title.trim() === '') {
              callback(new Error(`问题${i + 1}的标题不能为空`));
              return;
            }
            // 如果是单选或多选，检查选项
            if (question.optionType === 1 || question.optionType === 2) {
              if (!question.options || question.options.length === 0) {
                callback(new Error(`问题${i + 1}的选项不能为空`));
                return;
              }
              // 检查选项名称
              for (let j = 0; j < question.options.length; j++) {
                if (!question.options[j].name || question.options[j].name.trim() === '') {
                  callback(new Error(`问题${i + 1}的选项${j + 1}名称不能为空`));
                  return;
                }
              }
            }
          }
          callback();
        } else if (form.value.type === 4) {
          // 类型为4（发起倡议书）时，不需要投票选项
          callback();
        } else {
          callback();
        }
      }
    }],
    initiator: [{ required: true, message: "发起方不能为空", trigger: "blur" }],
    ratio: [{ 
      required: true, 
      trigger: "blur",
      validator: (rule, value, callback) => {
        if (form.value.type === 2) {
          if (!value || value < 0.001 || value > 100) {
            callback(new Error('通过比例必须在0.001-100之间'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      }
    }],
    signNum: [{ 
      required: true, 
      trigger: "blur",
      validator: (rule, value, callback) => {
        if (form.value.type === 4) {
          if (!value || value <= 0) {
            callback(new Error('目标签字人数必须大于0'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      }
    }],
  }
});

const { queryParams, form, rules } = toRefs(data);

const voteOptions = ref([{ name: '' }]) // 保留原有的，但不再使用
const voteQuestions = ref([{ title: '', remark: '', optionType: 1, limitType: 1, minNum: 2, maxNum: 3, fixedNum: 2, options: [{ name: '' }] }]) // 新增：投票问题结构，包含remark字段
const surveyQuestions = ref([{ title: '', optionType: 1, limitType: 1, minNum: 2, maxNum: 3, fixedNum: 2, options: [{ name: '' }] }])

// 禁用日期方法 - 禁用今天之前的日期
function disabledDate(time) {
  // 获取当前日期的开始时间（00:00:00）
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  
  // 禁用今天之前的日期
  return time.getTime() < today.getTime()
}

function addOption() {
  voteOptions.value.push({ name: '' })
}
function removeOption(idx) {
  if (voteOptions.value.length > 1) {
    voteOptions.value.splice(idx, 1)
  } else {
    // 如果只有一个选项，清空其内容而不是删除
    voteOptions.value[0].name = ''
  }
}

function addQuestion() {
  voteQuestions.value.push({ title: '', remark: '', limitType: 1, minNum: 2, maxNum: 3, fixedNum: 2, options: [{ name: '' }] })
}
function removeQuestion(idx) {
  if (voteQuestions.value.length > 1) {
    voteQuestions.value.splice(idx, 1)
  }
}
function addQuestionOption(qIdx) {
  voteQuestions.value[qIdx].options.push({ name: '' })
}
function removeQuestionOption(qIdx) {
  if (voteQuestions.value[qIdx].options.length > 1) {
    voteQuestions.value[qIdx].options.splice(-1, 1)
  }
}

function addSurveyQuestion() {
  surveyQuestions.value.push({ title: '', optionType: 1, limitType: 1, minNum: 2, maxNum: 3, fixedNum: 2, options: [{ name: '' }] })
}
function removeSurveyQuestion(idx) {
  if (surveyQuestions.value.length > 1) {
    // 收集要删除的问题及其子选项的optionId
    const questionToDelete = surveyQuestions.value[idx]
    const optionIdsToDelete = []
    
    // 收集子选项的optionId
    if (questionToDelete.options && questionToDelete.options.length > 0) {
      questionToDelete.options.forEach(option => {
        if (option.optionId) {
          optionIdsToDelete.push(option.optionId)
        }
      })
    }
    
    // 调用API删除这些optionId
    if (optionIdsToDelete.length > 0) {
      delVoteOption(optionIdsToDelete.join(',')).then(() => {
      }).catch(() => {
      })
    }
    
    surveyQuestions.value.splice(idx, 1)
  }
}
function addSurveyOption(qIdx) {
  surveyQuestions.value[qIdx].options.push({ name: '' })
}
function removeSurveyOption(qIdx) {
  if (surveyQuestions.value[qIdx].options.length > 1) {
    surveyQuestions.value[qIdx].options.splice(-1, 1)
  }
}

function removeSurveyOptionItem(qIdx, oIdx, optionId) {
  if (surveyQuestions.value[qIdx].options.length > 1) {
    // 收集要删除的选项的optionId
    if (optionId) {
      // 调用API删除这个optionId
      delVoteOption(optionId).then(() => {
      }).catch(() => {
      })
    }
    
    surveyQuestions.value[qIdx].options.splice(oIdx, 1)
  }
}

// 新增投票问题相关方法
function addVoteQuestion() {
  voteQuestions.value.push({ title: '', remark: '', optionType: 1, limitType: 1, minNum: 2, maxNum: 3, fixedNum: 2, options: [{ name: '' }] })
}

function removeVoteQuestion(idx) {
  if (voteQuestions.value.length > 1) {
    voteQuestions.value.splice(idx, 1)
  }
}

function addVoteQuestionOption(qIdx) {
  voteQuestions.value[qIdx].options.push({ name: '' })
}

function removeVoteQuestionOption(qIdx) {
  if (voteQuestions.value[qIdx].options.length > 1) {
    voteQuestions.value[qIdx].options.splice(-1, 1)
  }
}

// 处理投票限制类型变化
function handleVoteLimitTypeChange(qIdx) {
  if (!voteQuestions.value[qIdx]) return
  
  const question = voteQuestions.value[qIdx]
  
  switch(question.limitType) {
    case 1: // 区间限制（X-Y个）
      question.minNum = 2
      question.maxNum = 3
      break
    case 2: // 最少限制（至少X个）
      question.minNum = 2
      question.maxNum = 999
      break
    case 3: // 最多限制（最多X个）
      question.minNum = 0
      question.maxNum = 2
      break
    case 4: // 固定数量（只能X个）
      question.fixedNum = 2
      question.minNum = question.fixedNum
      question.maxNum = question.fixedNum
      break
    case 5: // 无限制
      question.minNum = 0
      question.maxNum = 999
      break
    default:
      question.minNum = 0
      question.maxNum = 999
      break
  }
}

// 处理固定数量变化（投票）
function handleFixedNumChange(qIdx) {
  if (!voteQuestions.value[qIdx]) return
  
  const question = voteQuestions.value[qIdx]
  question.minNum = question.fixedNum
  question.maxNum = question.fixedNum
}

// 处理问卷调查限制类型变化
function handleSurveyLimitTypeChange(qIdx) {
  if (!surveyQuestions.value[qIdx]) return
  
  const question = surveyQuestions.value[qIdx]
  
  switch(question.limitType) {
    case 1: // 区间限制（X-Y个）
      question.minNum = 2
      question.maxNum = 3
      break
    case 2: // 最少限制（至少X个）
      question.minNum = 2
      question.maxNum = 999
      break
    case 3: // 最多限制（最多X个）
      question.minNum = 0
      question.maxNum = 2
      break
    case 4: // 固定数量（只能X个）
      question.fixedNum = 2
      question.minNum = question.fixedNum
      question.maxNum = question.fixedNum
      break
    case 5: // 无限制
      question.minNum = 0
      question.maxNum = 999
      break
    default:
      question.minNum = 0
      question.maxNum = 999
      break
  }
}

// 处理固定数量变化（问卷调查）
function handleSurveyFixedNumChange(qIdx) {
  if (!surveyQuestions.value[qIdx]) return
  
  const question = surveyQuestions.value[qIdx]
  question.minNum = question.fixedNum
  question.maxNum = question.fixedNum
}

// 处理类型切换
function handleTypeChange(newType) {
  // 切换类型时重置相关数据结构，避免响应式数据冲突
  nextTick(() => {
    switch(newType) {
      case 1: // 投票
        voteQuestions.value = [{ title: '', remark: '', optionType: 1, limitType: 1, minNum: 2, maxNum: 3, fixedNum: 2, options: [{ name: '' }] }]
        surveyQuestions.value = [{ title: '', optionType: 1, limitType: 1, minNum: 2, maxNum: 3, fixedNum: 2, options: [{ name: '' }] }]
        break
      case 2: // 快速决议
        voteQuestions.value = [{ title: '', limitType: 1, minNum: 2, maxNum: 3, fixedNum: 2, options: [{ name: '' }] }]
        surveyQuestions.value = [{ title: '', optionType: 1, limitType: 1, minNum: 2, maxNum: 3, fixedNum: 2, options: [{ name: '' }] }]
        break
      case 3: // 问卷调查
        voteQuestions.value = [{ title: '', remark: '', optionType: 1, limitType: 1, minNum: 2, maxNum: 3, fixedNum: 2, options: [{ name: '' }] }]
        surveyQuestions.value = [{ title: '', optionType: 1, limitType: 1, minNum: 2, maxNum: 3, fixedNum: 2, options: [{ name: '' }] }]
        break
      case 4: // 发起倡议书
        voteQuestions.value = [{ title: '', remark: '', optionType: 1, limitType: 1, minNum: 2, maxNum: 3, fixedNum: 2, options: [{ name: '' }] }]
        surveyQuestions.value = [{ title: '', optionType: 1, limitType: 1, minNum: 2, maxNum: 3, fixedNum: 2, options: [{ name: '' }] }]
        break
      default:
        break
    }
    
    // 清空表单验证错误
    if (proxy.$refs.voteRef) {
      proxy.$refs.voteRef.clearValidate(['voteOptions'])
    }
  })
}

// 根据 minNum 和 maxNum 推断限制类型
function determineLimitType(minNum, maxNum) {
  if (minNum === maxNum && minNum > 0) {
    return 4 // 固定数量
  } else if (minNum === 0 && maxNum === 999) {
    return 5 // 无限制
  } else if (minNum > 0 && maxNum === 999) {
    return 2 // 最少限制
  } else if (minNum === 0 && maxNum > 0 && maxNum < 999) {
    return 3 // 最多限制
  } else if (minNum > 0 && maxNum > minNum && maxNum < 999) {
    return 1 // 区间限制
  } else {
    return 1 // 默认区间限制
  }
}

// 监听 voteOptions 和 voteQuestions
watch(voteQuestions, (val) => {
  if (form.value.type === 1 || form.value.type === 2) {
    form.value.voteOptions = val.map(question => ({
      title: question.title,
      remark: question.remark || '', // 添加remark字段（只有type=1时有值）
      optionType: question.optionType, // 添加optionType字段
      minNum: question.minNum, // 最少选择数
      maxNum: question.maxNum, // 最多选择数
      options: question.options.map(option => ({ 
        name: option.name,
        optionId: option.optionId 
      }))
    }))
  }
}, { deep: true })

watch(surveyQuestions, (val) => {
  if (form.value.type === 3) {
    form.value.voteOptions = val.map(question => ({
      title: question.title,
      optionType: question.optionType,
      minNum: question.minNum, // 最少选择数
      maxNum: question.maxNum, // 最多选择数
      options: question.options.map(option => ({ 
        name: option.name,
        optionId: option.optionId 
      }))
    }))
  }
}, { deep: true })

function reset() {
  form.value = {
    voteId: null,
    communityId: null,
    type: null,
    ratio: null,
    signNum: null,
    votePicture: null,
    voteTitle: null,
    voteContent: null,
    voteScope: [],
    voteViewScope: null,
    voteRule: null,
    startDate: null,
    endDate: null,
    dateRange: null,
    voteOptions: []
  };
  voteOptions.value = [{ name: '' }]
  voteQuestions.value = [{ title: '', remark: '', optionType: 1, limitType: 1, minNum: 2, maxNum: 3, fixedNum: 2, options: [{ name: '' }] }] // 包含remark字段
  surveyQuestions.value = [{ title: '', optionType: 1, limitType: 1, minNum: 2, maxNum: 3, fixedNum: 2, options: [{ name: '' }] }]
  proxy.resetForm("voteRef");
}
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增";
}
function handleUpdate(row) {
  console.log("row",row)
  if(!row){
    let id=ids.value[0]
    row=voteList.value.find(item => item.voteId == id)
  }
  reset();
  const _voteId = row.voteId || ids.value[0];
  getVote(_voteId).then(response => {
    form.value = response.data;
    if (form.value.voteScope && typeof form.value.voteScope === 'string') {
      form.value.voteScope = form.value.voteScope.split(',');
    } else {
      form.value.voteScope = [];
    }
    if (form.value.voteViewScope && typeof form.value.voteViewScope === 'string') {
      form.value.voteViewScope = form.value.voteViewScope.split(',');
    } else {
      form.value.voteViewScope = [];
    }

    form.value.dateRange = [form.value.startDate, form.value.endDate];
    
    // 根据类型处理投票选项数据
    if (form.value.type === 1) {
      // 投票：将扁平数组转换为多问题结构
      if (Array.isArray(form.value.voteOptions) && form.value.voteOptions.length) {
        // 按title分组
        const questionMap = new Map()
        form.value.voteOptions.forEach(item => {
          if (item.title && item.name) {
            if (!questionMap.has(item.title)) {
              const minNum = item.minNum || item.minSelect || 1
              const maxNum = item.maxNum || item.maxSelect || 1
              const limitType = determineLimitType(minNum, maxNum)
              
              questionMap.set(item.title, {
                title: item.title,
                remark: item.remark || '', // 添加remark字段
                optionType: item.optionType || 1,
                limitType: limitType,
                minNum: minNum,
                maxNum: maxNum,
                fixedNum: minNum === maxNum ? minNum : 2,
                options: []
              })
            }
            questionMap.get(item.title).options.push({ 
              name: item.name,
              optionId: item.optionId 
            })
          }
        })
        voteQuestions.value = Array.from(questionMap.values())
      } else {
        voteQuestions.value = [{ title: '', remark: '', optionType: 1, limitType: 1, minNum: 2, maxNum: 3, fixedNum: 2, options: [{ name: '' }] }]
      }
    } else if (form.value.type === 2) {
      // 快速决议：将扁平数组转换为多问题结构
      if (Array.isArray(form.value.voteOptions) && form.value.voteOptions.length) {
        // 按title分组
        const questionMap = new Map()
        form.value.voteOptions.forEach(item => {
          if (item.title && item.name) {
            if (!questionMap.has(item.title)) {
              const minNum = item.minNum || item.minSelect || 1
              const maxNum = item.maxNum || item.maxSelect || 1
              const limitType = determineLimitType(minNum, maxNum)
              
              questionMap.set(item.title, {
                title: item.title,
                limitType: limitType,
                minNum: minNum,
                maxNum: maxNum,
                fixedNum: minNum === maxNum ? minNum : 2,
                options: []
              })
            }
            questionMap.get(item.title).options.push({ 
              name: item.name,
              optionId: item.optionId 
            })
          }
        })
        voteQuestions.value = Array.from(questionMap.values())
      } else {
        voteQuestions.value = [{ title: '', limitType: 1, minNum: 2, maxNum: 3, fixedNum: 2, options: [{ name: '' }] }]
      }
    } else if (form.value.type === 3) {
      // 问卷调查：处理包含optionType的数据
      if (Array.isArray(form.value.voteOptions) && form.value.voteOptions.length) {
        // 按title分组
        const questionMap = new Map()
        form.value.voteOptions.forEach(item => {
          if (item.title) {
            if (!questionMap.has(item.title)) {
              const minNum = item.minNum || item.minSelect || 1
              const maxNum = item.maxNum || item.maxSelect || 1
              const limitType = determineLimitType(minNum, maxNum)
              
              questionMap.set(item.title, {
                title: item.title,
                optionType: item.optionType || 1,
                limitType: limitType,
                minNum: minNum,
                maxNum: maxNum,
                fixedNum: minNum === maxNum ? minNum : 2,
                options: []
              })
            }
            if (item.name) {
              questionMap.get(item.title).options.push({ 
                name: item.name,
                optionId: item.optionId 
              })
            }
          }
        })
        surveyQuestions.value = Array.from(questionMap.values())
      } else {
        surveyQuestions.value = [{ title: '', optionType: 1, limitType: 1, minNum: 2, maxNum: 3, fixedNum: 2, options: [{ name: '' }] }]
      }
    }
    
    open.value = true;
    title.value = "修改投票";
  });
}
function handleView(row) {
  router.push({
    path: '/house/votingrecords',
    query: {
      voteId: row.voteId
    }
  })
}

/** 查询投票列表 */
async function getList() {
  let user=await userStore.getInfo()
 
  loading.value = true;
  // 处理创建时间参数
  const params = { ...queryParams.value };
  if (params.createDate && Array.isArray(params.createDate)) {
    params.startCreateDate = params.createDate[0];
    params.endCreateDate = params.createDate[1];
    delete params.createDate;
  }
  listVote(params).then(response => {
    voteList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询小区列表 */
function getCommunityList() {
  listCommunity({ pageNum: 1, pageSize: 1000 }).then(response => {
    communityOptions.value = response.rows;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.voteId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["voteRef"].validate(valid => {
    if (valid) {
      // 根据类型处理投票选项数据
      if (form.value.type === 1) {
        // 投票：将多问题结构转换为扁平数组，包含optionType
        const flatOptions = []
        voteQuestions.value.forEach(question => {
          question.options.forEach(option => {
            flatOptions.push({
              title: question.title,
              remark: question.remark || '', // 添加remark字段
              optionType: question.optionType, // 添加optionType字段
              minNum: question.minNum, // 最少选择数
              maxNum: question.maxNum, // 最多选择数
              name: option.name,
              optionId: option.optionId
            })
          })
        })
        form.value.voteOptions = flatOptions
        console.log(form.value.voteOptions)
       
      } else if (form.value.type === 2) {
        // 快速决议：将多问题结构转换为扁平数组
        const flatOptions = []
        voteQuestions.value.forEach(question => {
          question.options.forEach(option => {
            flatOptions.push({
              title: question.title,
              minNum: question.minNum, // 最少选择数
              maxNum: question.maxNum, // 最多选择数
              name: option.name,
              optionId: option.optionId
            })
          })
        })
        form.value.voteOptions = flatOptions
      } else if (form.value.type === 3) {
        // 问卷调查：将多问题结构转换为扁平数组，包含optionType
        const flatOptions = []
        surveyQuestions.value.forEach(question => {
          if (question.optionType === 3) {
            // 填空类型，不需要选项
            flatOptions.push({
              title: question.title,
              optionType: question.optionType,
              minNum: question.minNum, // 最少选择数
              maxNum: question.maxNum // 最多选择数
            })
          } else {
            // 单选和多选类型，需要选项
            question.options.forEach(option => {
              flatOptions.push({
                title: question.title,
                optionType: question.optionType,
                minNum: question.minNum, // 最少选择数
                maxNum: question.maxNum, // 最多选择数
                name: option.name,
                optionId: option.optionId
              })
            })
          }
        })
        form.value.voteOptions = flatOptions
      } else if (form.value.type === 4) {
        // 发起倡议书：不需要投票选项
        form.value.voteOptions = []
      }
      
      const payload = { ...form.value };
      if (Array.isArray(payload.dateRange) && payload.dateRange.length === 2) {
        payload.startDate = payload.dateRange[0];
        payload.endDate = payload.dateRange[1];
      }

      delete payload.dateRange;
      if (Array.isArray(payload.voteScope)) {
        payload.voteScope = payload.voteScope.join(',');
      }
      if (Array.isArray(payload.voteViewScope)) {
        payload.voteViewScope = payload.voteViewScope.join(',');
      }
      console.log(payload)
    
      if (payload.voteId != null) {
        updateVote(payload).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addVote(payload).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _voteIds = row.voteId || ids.value;
  proxy.$modal.confirm('是否确认删除投票编号为"' + _voteIds + '"的数据项？').then(function() {
    return delVote(_voteIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

function handleImportSuccess(response, file, fileList) {
  proxy.$modal.msgSuccess('上传成功')
  importDialogVisible.value = false
  // 可在此处刷新列表等
}

function handleExceed(files, uploadFiles) {
  // 超出限制时清空并只保留最新文件
  this.$refs.upload.clearFiles()
  this.$refs.upload.handleStart(files[0])
}

function getRoles(){ //当是pda人员的时候 默认让她是投票
  let roles=userStore.roles
  let pdaRoles=["pda","pda审核"] // 可以在这里添加更多pda相关角色
  
  // 检查是否有pda相关角色，都默认为投票类型
  if(pdaRoles.some(role => roles.includes(role))){
    queryParams.value.type = 1  // 默认为投票类型
  }
}

onMounted(() => {
  getRoles()
  getList();
  getCommunityList();
});
</script>

